<?php
namespace app\common\service\lib;
/**
 * 百度云内容审核
 * @param  [type] $type    内容类型 image msg
 * @param  [type] $content 内容
 * @return [type]          [description]
 */
class BaiduApi{
    protected $url;
    protected $grant_type;
    protected $client_id;
    protected $client_secret;
    protected $tokenUrl;
    public function __construct()
    {
        $this->url = config('setting.sensitive.url');
        $this->grant_type = config('setting.sensitive.grant_type');
        $this->client_id = config('setting.sensitive.client_id');
        $this->client_secret = config('setting.sensitive.client_secret');
        $this->tokenUrl = config('setting.sensitive.tokenUrl');
    }
    /**
     * Author:William
     * @param string $text 文本内容
     * @return array
     */
    public function index(string $text)
    {
        $url = $this->url;
        $post_data['grant_type'] = $this->grant_type;
        $post_data['client_id'] =$this->client_id;
        $post_data['client_secret'] = $this->client_secret;
        $o = "";
        foreach ($post_data as $k => $v) {
            $o .= "$k=" . urlencode($v) . "&";
        }
        $post_data = substr($o, 0, -1);
        $res = BaiduApi::request_post($url, $post_data);
        $data = json_decode($res, true);
        $token = $data['access_token'];
        $tokenUrl = "$this->tokenUrl" . $token;
        $bodys = array(
            'text' => $text,
        );
        $res = self::request_post($tokenUrl, $bodys);
        $res= json_decode($res,true);
        return $res;
    }

    /**
     * Author:William
     * @param string $url
     * @param string $param
     * @return bool|string
     */
    public static function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $curl = curl_init();//初始化curl
        curl_setopt($curl, CURLOPT_URL, $postUrl);//抓取指定网页
        curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($curl);//运行curl
        curl_close($curl);
        return $data;
    }
}